﻿using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Castle.Core.Configuration;
using Castle.Facilities.NHibernateIntegration;
using NHATMSample.Models;
using NHibernate.ByteCode.Castle;
using NHibernate.Cfg;
using NHibernate.Connection;
using NHibernate.Dialect;
using NHibernate.Driver;

namespace NHATMSample {
    public class NHConfigBuilder : IConfigurationBuilder {
        private readonly string path;

        public NHConfigBuilder(string path) {
            this.path = path;
        }

        public Configuration GetConfiguration(IConfiguration config) {
            string db = Path.Combine(path, "test.db");
            return new Configuration()
                .AddProperties(new Dictionary<string, string> {
                    {Environment.ConnectionDriver, typeof (SQLite20Driver).FullName},
                    {Environment.ProxyFactoryFactoryClass, typeof (ProxyFactoryFactory).AssemblyQualifiedName},
                    {Environment.Dialect, typeof (SQLiteDialect).FullName},
                    {Environment.ConnectionProvider, typeof (DriverConnectionProvider).FullName},
                    {Environment.ConnectionString, string.Format("Data Source={0};Version=3;New=True;", db)},
                })
                .AddXmlString(person_xml);
        }

        private static readonly string person_xml =
       @"<?xml version='1.0' encoding='utf-8' ?>
<hibernate-mapping xmlns='urn:nhibernate-mapping-2.2' default-lazy='true'>
    <class table='Person' name='" + typeof(Person).AssemblyQualifiedName + @"'>
        <id name='Id'>
            <generator class='native'/>
        </id>
        <property name='Name'/>
        <set name='Children' inverse='true'>
            <key column='Id' />
            <one-to-many class='" + typeof(Person).AssemblyQualifiedName+@"' />
        </set>    
    </class>
</hibernate-mapping>
";
    }
}